package com.xuanwei.admin.controller;

import com.xuanwei.core.response.ResultVO;
import com.xuanwei.core.util.FastDFSClient;
import com.xuanwei.core.util.GenerateCodeImage;
import com.xuanwei.xwcommon.consts.CacheName;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;


/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/4/16 17:16
 **/
@Controller
@RequestMapping("/api")
@Slf4j
public class CommonController {

    @Autowired
    private FastDFSClient fastDFSClient;

    @RequestMapping(value = "checkCode", method = RequestMethod.GET)
    public void imageCode(HttpServletRequest request, HttpServletResponse response){
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        try (OutputStream os = response.getOutputStream()){
            GenerateCodeImage generateCodeImage = new GenerateCodeImage();
            String code = generateCodeImage.getCode();
            log.info("验证码----"+code);
            HttpSession session = request.getSession();
            session.setAttribute(CacheName.CODE,code);
            session.setMaxInactiveInterval(900);
            generateCodeImage.write(os);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "upload.do",method = RequestMethod.POST)
    @ResponseBody
    public ResultVO upload(MultipartFile file) throws IOException {
        String s = fastDFSClient.uploadImage(file);
        return ResultVO.successResult("上传成功",s);
    }

}
